
const dao = require("../dao/post")
const response = require("../utils/response")
const { checkauth } = require("../utils/check");

/**
 * 添加一个新帖子
 * @param {*} data {user_id, title, content, imgs, tags}
 */
async function add_post(data) {
    let auth = await checkauth(data.secret_id, data.user_id);
    if (!auth) {
        return response.forbidden("权限错误");
    }
    let pid = await dao.add_post(data.user_id, data.title, data.content, data.imgs, data.tags);
    return response.ok({
        post_id: pid,
    })
}

/**
 * 删除一个帖子，同步删除点赞，star和comment
 * @param {*} data {post_id}
 */
async function del_post(data) {
    var user_id = await dao.get_user_id(data.post_id);
    let auth = await checkauth(data.secret_id, user_id);
    if (!auth) {
        return response.forbidden("权限错误");
    }
    await dao.del_post(data.post_id);
}

/**
 * 修改帖子
 * @param {*} data {post_id, title, content, imgs, tags}
 */
async function update_post(data) {
    var user_id = await dao.get_user_id(data.post_id);
    let auth = await checkauth(data.secret_id, user_id);
    if (!auth) {
        return response.forbidden("权限错误");
    }
    await dao.update_post(data.post_id, data.title, data.content, data.imgs, data.tags);
}

/**
 * 阅读量+1
 * @param {*} data {secret_id, user_id, post_id}
 */
async function add_read(data) {
    let auth = await checkauth(data.secret_id, data.user_id);
    if (!auth) {
        await dao.add_read(data.post_id);
    } //无需提示
}

/**
 * 获取单个post的完整信息
 * @param {*} data {user_id, post_id}
 */
async function get_fullpost(data) {
    return response.ok(await dao.get_fullpost(data.user_id, data.post_id));
}

module.exports = {
    add_post: add_post,
    del_post: del_post,
    update_post: update_post,
    add_read: add_read,
    get_fullpost: get_fullpost,
}
